package com.wang.servlet;

import com.wang.utils.ConstantsUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author wr
 * @date 2021/10/28 15:28
 */
@WebServlet(name = "download", urlPatterns = "/home/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        String filePath = req.getServletContext().getRealPath(ConstantsUtil.Storage.STORAGE_ROOT) + req.getSession().getAttribute(ConstantsUtil.Login.USER_KEY) + "/" + filename;
        File file = new File(filePath);
        if(file.exists()){
            FileInputStream fis = new FileInputStream(file);
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-Disposition", "attachment; filename="+filename);
            ServletOutputStream out = resp.getOutputStream();
            byte[] bt = new byte[1024];
            int length = 0;
            while((length=fis.read(bt))!=-1){
                out.write(bt,0,length);
            }
            out.close();
        }else {
            resp.getWriter().write("<h1>文件不存在</h1>");
        }
    }
}
